package saleMarket.dao.authority;

import saleMarket.domain.authority.Actor;
import saleMarket.domain.authority.ActorAssRole;
import saleMarket.domain.authority.Role;
import saleMarket.service.WarehouseService;
import saleMarket.service.authority.ActorService;
import saleMarket.service.authority.RoleService;
import util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ActorAssRoleDao {
    private static final ActorAssRoleDao actorAssRoleDao = new ActorAssRoleDao();

    private ActorAssRoleDao() {
    }

    public static ActorAssRoleDao getInstance() {
        return actorAssRoleDao;
    }

    /**
     * 根据id，查找各个子类的对象
     *
     * @param connection
     * @param id         目标对象的id
     * @return id对应的目标对象
     * @throws SQLException
     */
    public ActorAssRole find(Connection connection, int id) throws SQLException {
        //先后在Student和Teacher中查找相应的id
        ActorAssRole desiredActorAssRole = null;
        //编辑预编译语句
        PreparedStatement find_pstmt = connection.prepareStatement
                ("SELECT * FROM actorAssRole WHERE id = ?");
        //设置预编译参数
        find_pstmt.setInt(1,id);
        //执行查询并获取查询结果
        ResultSet find_resultSet = find_pstmt.executeQuery();
        //赋值
        if (find_resultSet.next()){
            Actor actor = ActorService.getInstance().
                    find(find_resultSet.getInt("actor_id"));
            Role role = RoleService.getInstance().
                    find(find_resultSet.getInt("role_id"));

            //创建相应的顾客对象
            desiredActorAssRole = new ActorAssRole(id,actor,role);
        }
        //释放资源
        JdbcHelper.close(find_resultSet,find_pstmt);
        //返回查询结果
        return desiredActorAssRole;
    }
}
